package com.sky.common.exception;

import com.sky.common.api.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.xml.soap.SOAPException;
import java.net.ConnectException;
import java.util.Objects;

/**
 * 异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(GlobalException.class)
    public Result<Object> handleApiException(GlobalException e) {
        log.error("自定义GlobalException 抛出:", e);
        return Result.failed(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.failed();
    }

    /**
     * 拦截JSON参数校验
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> bindJsonParamException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String msg = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
        log.error("参数校验异常拦截：{}", msg);
        return Result.failed(msg);
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({SOAPException.class, ConnectException.class})
    public Result<Object> bindSOAPAndConnectException(Exception e){
        if(e instanceof SOAPException)
            log.error("SOAP异常{}",e.getMessage());
        else
            log.error("Onvif连接异常{}", e.getMessage());

        return Result.failed("Onvif连接异常");
    }

}
